Vue.component('exam-title', {
  template: '#exam-title',
  data() {
    return {
      points: 0,
      showPoints: false,
    }
  },
  created() {
    Bus.$on('handleHandClick', scores => {
      this.points = scores;
      this.showPoints = true;
    })
  }
});
// 侧边栏组件
Vue.component('exam-side', {
  template: '#exam-side',
  data() {
    return {
      sideWrapperIsFixed: false,
      sideOffsetTop: 0,
      sideOffsetLeft: 0,
      isFixed: false,
      styleFixed: null,
      styleGreen: null, //正确答案显示绿色
      styleRed: null, //错误答案显示红色
      sideList: [],
      sideItemList: [], //答题卡上数字列表
      itemIndex: null, 
      count: 0, //已做题的数量
      remainingTime: '00:00:00', //初始化倒计时
      showCal: false, //控制计算器的显示
      scoreList: [], //计算分数的数组
      scores: 0, //总分数
      showAnswer: true, //传递给exam-main组件，用以显示答案，解析
      isDisabled: false, //是否禁用提交按钮
    };
  },
  created() {
    Bus.$on('exam-main', list => {
      this.sideList = list;
      this.sideItemList = newArray(this.sideList.length, '') //创建新的空数组
      this.scoreList = newArray(this.sideList.length, 0)
    });
    Bus.$on('mainToSide', (index, id, answerScore) => {
      this.sideItemList.splice(index, 1, id); // 给空数组的对应的index项添加内容，如果对应index有值，相应的给答题卡上的数字添加背景颜色
      this.itemIndex = index;
      var sideItemArr = this.sideItemList.filter(item => item);
      this.count = sideItemArr.length;
      this.scoreList.splice(index, 1, answerScore);
      this.scores = this.sumArr(this.scoreList);
    });
  },
  methods: {
    //点击计算器按钮
    onCalClick() {
      this.showCal = true;
    },
    onCalClose() {
      this.showCal = false;
    },
    //计算总分数函数
    sumArr(arr){
      var sum = 0;
      arr.forEach(function(val) {
        sum += val;
      })
      return sum;
    },

    //点击答题卡上的数字把index传递给考试题目组件
    handleSideSpanClick(index) {
      Bus.$emit('handleSideSpanClick', index)
    },
    // 点击提交按钮
    handleHandClick() {
      this.isDisabled = true;
      Bus.$emit('handleHandClick', this.scores);
      Bus.$emit('sideToMain', this.showAnswer, this.isDisabled);
      // 正确答案显示绿色
      this.styleGreen = {
        background: 'green',
        color: '#fff'
      };
      //错误答案显示红色
      this.styleRed = {
        background: '#f06000',
        color: '#fff',
      };
      //点击交卷后回到顶部
      document.body.scrollTop = document.documentElement.scrollTop = 0;
    },
    // 滚动到顶部固定
    handleScroll: function() {
      var scrollTop = window.pageYOffset   ||
        document.documentElement.scrollTop ||
        document.body.scrollTop;
      this.sideOffsetTop = document.querySelector('.side-wrapper').offsetTop;
      if (scrollTop > this.sideOffsetTop) {
        this.isFixed = true;
      }
      this.sideOffsetTop = 322;
      if (scrollTop < 402) {
        this.isFixed = false;
      }
    },
    // 改变宽度适应
    changeWidth: function(left) {
      this.styleFixed = {
        position: 'fixed',
        top: '5px',
        left: `${left}px`
      };
    },
    // 格式化倒计时时间格式
    formate(time) {
      if(time>=10){
        return time
      }else{
        return `0${time}`
      }
    },
    //倒计时
    countDown: function(times = 100) {
      var h = Math.floor(times / 60);
      var m = Math.floor(times - h * 60) - 1;
      var s = 60;
      var timer = setInterval(() => {
        s --;
        if (s < 0) {
          m --;
          s = 59;
        }
        if(m < 0) {
          h--;
          m = 59;
        }
        if(h < 0) {
          h = m = s = 0;
          clearInterval(timer)
        }
        this.remainingTime = this.formate(h) + ':' + this.formate(m) + ':' + this.formate(s);
      }, 1000)
    }
  },
  mounted() {
    window.addEventListener('scroll', this.handleScroll); //监听上下滚动事件
    var left = document.querySelector('.side-wrapper').getBoundingClientRect().left;
    this.changeWidth(left);
    window.onresize = () => { // 监听窗口改变
      var newleft = document.querySelector('body').clientWidth;
      this.changeWidth(newleft - 430);
    };
    this.countDown();
  },
  destroyed() {
    window.removeEventListener('scroll', this.handleScroll); // 移除监听事件
  }
});

// 考试题目组件
Vue.component('exam-main', {
  template: '#exam-questions',
  data() {
    return {
      questionsList: [],
      inputValue: '',
      selectrdList: [],
      answerShow: false,
      answerScore: 0,
      isRadioDisabled: false,  //交卷后是否禁用单选按钮
    };
  },
  methods: {
    onRadioClick(e, index, id) {
      this.inputValue = e.target.value;
      this.selectrdList.splice(index, 1, this.inputValue);
      if(this.inputValue === this.questionsList[index].answer) {
        this.answerScore = 4
      }else{
        this.answerScore = 0
      }
      Bus.$emit('mainToSide', index, id, this.answerScore);
    }
  },
  created() {
    axios.get('http://localhost:3000/result').then(res => {
      this.questionsList = res.data;
      Bus.$emit('exam-main', this.questionsList);
      this.selectrdList = newArray(this.questionsList.length, '')
    });
    Bus.$on('handleSideSpanClick', index => {
      this.$refs.questions[index].scrollIntoView()
    });
    Bus.$on('sideToMain', (showAnswer, isDisabled) => {
      this.answerShow = showAnswer;
      this.isRadioDisabled = isDisabled;
    })
  }
});

window.Bus = new Vue();

// 创建新数组函数
function newArray(len, item) {
  var arr = new Array(len);
  for (var i = 0; i < arr.length; i++) {
    arr[i] = item;
  }
  return arr;
}
new Vue({
  el: '#vue-app'
});

